package com.cw.utils.java.ip;


import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Random;

public class IPAddressUtils {

    public static String getLocalIP(){
        String localip = null;
        String netip = null;

        Enumeration<NetworkInterface> netInterfaces = null;

        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        InetAddress ip = null;
        boolean finded = false;
        while(netInterfaces.hasMoreElements() && !finded){
            NetworkInterface ni = netInterfaces.nextElement();
            Enumeration<InetAddress> address = ni.getInetAddresses();
            while (address.hasMoreElements()) {
                ip = address.nextElement();
                if(!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1){
                    netip = ip.getHostAddress();
                    finded = true;
                    break;
                } else if(ip.isSiteLocalAddress() && ! ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1){
                    localip = ip.getHostAddress();
                }
            }
        }

        String last = null;
        if(netip != null && !"".equals(netip)){
            last = netip.substring(netip.lastIndexOf('.')+1);
        } else{
            last = localip.substring(localip.lastIndexOf('.') +1);
        }
        return last;
    }
}
